<?php

namespace app\admin\controller\baobiao;

use app\common\controller\Backend;
use think\Db;
use think\Session;
/**
 * 物料统计
 * todo
 * 成本报表01-物料收发存业务流程明细
 * todo
 * 收发存业务流程明细表为月末核对调整使用，除财务人员需要外，暂未确定需要分配至哪些角色，需要增加在后台手动推送或者手动分配的方式
 *
 * @icon fa fa-circle-o
 */
class Material extends Backend
{

    /**
     * Type模型对象
     * @var \app\admin\model\disi\
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\m\Apply;
    }

      /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $params = [];
        $admin = Session::get();
        //厂长，只查看对应厂数据
        if(!empty($admin['factory_id'])){
            $params['a.admin_id'] = $admin['id'];
        }

        // TODO   需求:
        // 收发存明细:  包括:    调入,调出, 采购, 销售, 领用    等全部的记录
        //    表  m_apply  +  m_stockbill   +  是否有额外销售单,额外领用单;
        //  todo   解决方法1:  把 m_apply的数据,m_stockbill的数据, 合并到收发存业务明细的记录表 ;

        $list = Db::name('m_apply')
        ->alias('a')
        ->join("m_info b","a.info_id = b.id",'left')
        ->join("depot c","b.depot_id = c.id",'left')
        ->join("material d","b.mmaterial_id = d.id",'left')
        ->join("mafactory e","b.mafactory_id = e.id",'left')
        ->join("mcategory f","b.mcategory_id = f.id",'left')
        ->field("a.*,DATE_FORMAT(a.createtime,'%y.%m.%d') as create_date,b.code,b.name,b.specs,b.unit,b.price,b.merge_name,c.name as depot,d.name as material,e.name as factory,f.name as category,(a.num*b.price) as total_price")
        ->where($params)
        ->where($where)
        ->where(['a.status' => '已通过'])
        ->order($sort, $order)
        ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    
}
